
#include "BUtils.h"


using namespace std;
using namespace blueberry;

BBuffer::BBuffer(int _iCurMax)
{
	i_CurrentBufLen = 0;
	i_CurrentMaxBufLen = _iCurMax;
	z_DataBuffer = new char[i_CurrentMaxBufLen + 1];
	z_DataBuffer[0] = 0;
}
BBuffer::~BBuffer()
{
	delete[] z_DataBuffer;
	z_DataBuffer = NULL;

}
BMassBuffer::BMassBuffer() :	BBuffer(B_INIT_MASS_BUF_LEN)
{

	//	ui_UpdateCount = 0;
}

void BMassBuffer::Append(const char* _zBuffer, int _iBufLen)
{
	//	cout << "APPENDED Buffer Len: " << i_CurrentBufLen << endl;
	int iTotalLen = i_CurrentBufLen + _iBufLen;
	if (iTotalLen > B_INIT_MASS_BUF_LEN)
	{
	/*	int iOverLen = iTotalLen - INIT_MASS_BUF_LEN;
		i_CurrentBufLen -= iOverLen;
		memmove(z_DataBuffer, z_DataBuffer + iOverLen, i_CurrentBufLen);
		memcpy(z_DataBuffer + i_CurrentBufLen, _zBuffer, _iBufLen);
	*/
		//		i_CurrentBufLen += _iBufLen;
		//		cout << "Buffer over run " << ui_UpdateCount  << endl;
		DeleteFromStart( B_INIT_MASS_BUF_DEL_LEN);
	}
	//else
	//{
	memcpy(z_DataBuffer + i_CurrentBufLen, _zBuffer, _iBufLen);
	i_CurrentBufLen += _iBufLen;

	//}
	z_DataBuffer[ i_CurrentBufLen] = 0;


}
void BNormBuffer::Append(const char*_zBuffer, int _iBufLen)
{
	int iTotalLen = i_CurrentBufLen + _iBufLen;
	if (iTotalLen > i_CurrentMaxBufLen)
	{
		//std::cout<<"Buffer size increased to "<<i_CurrentMaxBufLen<<std::endl;
		i_CurrentMaxBufLen = iTotalLen + i_IncLen ;
		char * zTBuf = new char[i_CurrentMaxBufLen + 1];

		memcpy( zTBuf, z_DataBuffer, i_CurrentBufLen);
		memcpy( zTBuf + i_CurrentBufLen, _zBuffer, _iBufLen);
		i_CurrentBufLen = iTotalLen;
		char * zTDel = z_DataBuffer;
		z_DataBuffer = zTBuf;
		delete [] zTDel;
		cout << "BNormBuffer reallocated " << i_CurrentMaxBufLen << endl;
	}
	else
	{
		memcpy(z_DataBuffer + i_CurrentBufLen, _zBuffer, _iBufLen);
		i_CurrentBufLen += _iBufLen;

	}
	z_DataBuffer[ i_CurrentBufLen] = 0;
}
BNormBuffer::BNormBuffer(int _iInitBufLen , int _iIncLen ) :	BBuffer(_iInitBufLen)
{
	i_IncLen = _iIncLen;
}


BMassBuffer::~BMassBuffer()
{

}
BNormBuffer::~BNormBuffer()
{

}
void BBuffer::DeleteFromStart(int _iDelLen)
{
	memmove(z_DataBuffer, z_DataBuffer + _iDelLen, i_CurrentBufLen - _iDelLen);
	i_CurrentBufLen = i_CurrentBufLen - _iDelLen;
	z_DataBuffer[ i_CurrentBufLen] = 0;
	//	cout << "After del Buffer len: " << i_CurrentBufLen << endl;
	//	z_DataBuffer[ i_CurrentBufLen] = 0;
}
BFixedBuffer::BFixedBuffer():BBuffer(B_PKT_SEND_SIZE_MAX)
{
	ui_SequenceNumber = 0;
}
void BFixedBuffer::SetBuffer(const char * _zBuffer, int _iBufLen, UInt _uiSeqNo)
{
	memcpy(z_DataBuffer,_zBuffer,_iBufLen);
	i_CurrentBufLen = _iBufLen;
	ui_SequenceNumber = _uiSeqNo;
}
BFixedBuffer::~BFixedBuffer()
{

}
